from PIL import ImageGrab
import cv2
import numpy as np

from test.win.mouse import mouseMove, mouseClick

# 从当前屏幕截图查找图片
def mathc_img(Target, value=0.8):
    try:

        #全屏截图
        bbox = (576,188, 1057,628)
        im = np.array(ImageGrab.grab(bbox))
        # im = np.array(ImageGrab.grab())
        img_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
        #读取目标查找图片
        template = cv2.imread(Target, 0)
        #匹配，返回相似度
        res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
        threshold = value
        loc = np.where(res >= threshold)
        w, h = template.shape[::-1]
        for pt in zip(*loc[::-1]):
            cv2.rectangle(img_gray, pt, (pt[0] + w, pt[1] + h), (7, 249, 151), 2)
        cv2.imshow('Detected', img_gray)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        return (int(loc[1][0]), int(loc[0][0]))
    except:
        raise Exception('未匹配到图片')


def imageSearchClick(Target, x_, y_):
    # mouseMove(0, 0)
    x, y = mathc_img(Target)
    print("x :" + str(x) + "y:" + str(y))
    mouseMove(x + x_, y + y_)
    print(f"x :{x + x_},y:{y + y_}")
    mouseClick()
    # mouseMove(0, 0)


if __name__ == '__main__':
    # x, y = mathc_img(r'I:\pythonSolution\projects\sw4sy\test\imageDeal\match_need2.png')
    # x, y = mathc_img(r'I:\pythonSolution\projects\sw4sy\resources\img\match_need2.png')
    # mouseMove(x, y)
    # imageSearchClick(r'I:\pythonSolution\projects\sw4sy\resources\img\yingxiongshilian_tongguan.png', 461,439)
    # imageSearchClick(r'I:\pythonSolution\projects\sw4sy\resources\img\shouye.png', 942,643)
    # imageSearchClick(r'I:\pythonSolution\projects\sw4sy\test\imageDeal\20200211174111.png', 298,222)
    imageSearchClick(r'I:\pythonSolution\projects\sw4sy\test\imageDeal\match_need3.png', 576,188)
    # imageSearchClick(r'dir2.png', 20, 5)
    # mouseMove(379, 81)
    # mouseClick()
